package org.speed.jdk;

import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.management.Notification;
import javax.management.NotificationEmitter;
import javax.management.NotificationListener;
import javax.management.openmbean.CompositeData;

public class OutOfMemoryDemo {

	public static void main(String[] args) {
		
		
new Thread(new Runnable() {
			
			@Override
			public void run() {
				while (true) {
					
					List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
					for (GarbageCollectorMXBean mbean : beans) {
						if(mbean instanceof NotificationEmitter ) {
							 ((NotificationEmitter) mbean).addNotificationListener(new NotificationListener() {
								@Override
								public void handleNotification(Notification notification, Object handback) {
									
									CompositeData cd = (CompositeData) notification.getUserData();
									//cd.getCompositeType().getTypeName();
									Set<String> keySet = cd.getCompositeType().keySet();
									for (String key : keySet) {
										System.out.println("key=" + key  + ",value=" + cd.get(key));
									}
									
									String type = notification.getType();
									String message = notification.getMessage();
									Object userData = notification.getUserData();
									System.out.println("type=" + type + ",message=" + message + ",userData=" + userData);
								}
								 
							 }, null, null);
						}
					}
					
					
					try {
						Thread.sleep(1000 * 10);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
				}
				
			}
		}).start();



		int count = 0;
        List<Object> list = new ArrayList<Object>();
        while(true){
        	
            list.add(new Object());
            
            try {
				Thread.sleep(1000 * 2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            //System.out.println(++count);
        }

	}

}
